function send() {
	Sheet.createVocabulary();
	//Sheet.addTerm(new Term("cat", "кот"));
}

/** Here we will have private memebers :). */
Sheet = new function() {

  var vocTableName = 'Vocabulary';
  var documentName = bgPage.SHEET_VOC_NAME;
  
  // Amount of cell in one row is equals to amount of fields in class Term
  var cellInRow = 7;
  
  var baseUrl = bgPage.SHEETLIST_SCOPE;
  
  /** Default headers and query parameters.  */
  var defaultParameters = {
    headers: {
      'GData-Version': '3.0'
    },
    parameters: {
      'alt': 'json'
    }
  };
  
  /** Flag about main work sheet. */
  var dictionaryWorkSheetPresent = false;
  /** Document key. */
  var documentKey = null;
  
  function defaultResultProcessing(response, xhr, callback) {
    if (xhr.status != 200 && xhr.status != 201) {
      console.log(response);
      return;
    }
    if (callback) { callback(JSON.parse(response), xhr); }
  }
  
  /** Check documents, find our one or create. */
  function processListResults(data, xhr, callback) {
    var index = data.feed.entry.map(function(e){ return (e.title.$t) }).indexOf(documentName); 
    if (-1 == index) {
      doCreateVocabulary(callback);
      console.log("vocabulary will be created");
    } else {
      setDocumentKey(data.feed.entry[index].id.$t); 
      if (callback) { callback(documentKey); }
    }
  }
  
  function processWorkSheetResults(data, xhr, callback) {
    var index = data.feed.entry.map(function(e){ return (e.title.$t) }).indexOf(vocTableName);
    if (index != -1) {
      console.log('Dictionary is present');
      if (callback) { callback(); }
    } else {
      console.log('Need to create dictionary');
      doCreateMainWorkSheet(callback);
    }
  }
  
  function processCreationVocabulary(response, xhr, callback) {
    console.log(response);
  }
  
  function setDocumentKey(url) {
    // var index = url.lastIndexOf('/'); - don't know why it's stopped working with backslash
	  
    var index = url.lastIndexOf('%3A');
    documentKey = url.substring(index + 3);
  }
  
  function constructAtomXml(docTitle) {
    var atom = ["<?xml version='1.0' encoding='UTF-8'?>", 
                '<entry xmlns="http://www.w3.org/2005/Atom">',
                '<category scheme="http://schemas.google.com/g/2005#kind"', 
                ' term="http://schemas.google.com/docs/2007#', 'spreadsheet', '"/>',
                '',
                '<title>', docTitle, '</title>',
                '</entry>'].join('');
    return atom;
  }
  
  function constructContentBody(title) {
    var body = ['--END_OF_PART\r\n',
                'Content-Type: application/atom+xml;\r\n\r\n',
                constructAtomXml(title), '\r\n',
                '--END_OF_PART\r\n',
                'Content-Type: ', 'text/csv', '\r\n\r\n',
                '', '\r\n',
                '--END_OF_PART--\r\n'].join('');
     return body;
  }

  function buildParameters(params) {
    for (var part in defaultParameters) {
      if (!params[part]) { params[part] = {}; }
      for (var name in defaultParameters[part]) {
        if (!params[part][name]) { params[part][name] = defaultParameters[part][name]; }
      }
    }
    return params;
  }
  
  function apiCall(url, callback, parameters) {
	var targetUrl = baseUrl + url; 
	if (0 == url.indexOf("https://")) {
		targetUrl = url;
	}
    console.log('Call ' + targetUrl);
    bgPage.oauth.sendSignedRequest(
        targetUrl, 
        function(response, xhr) {
          console.log('Response ' + xhr.status + ' for ' + targetUrl);
          defaultResultProcessing(response, xhr, callback); 
        }, 
        buildParameters(parameters)
    );
  }
  
  function doCreateVocabulary(callback) {
	console.log("Creating vocabulary with name " + documentName);
    apiCall(bgPage.DOC_FEED_URL, function(feed, xhr) {
    		// if vocabulary was created then
    		// 1. saving worksheet-key 2. creating a worksheet
    		setDocumentKey(feed.entry.id.$t);
    		doCreateMainWorkSheet(processWorkSheetResults); 
    	}, {
      'method': 'POST',
      'headers': {
        'Content-Type': 'multipart/related; boundary=END_OF_PART'
      },
      'body': constructContentBody(documentName)
    });
  }

  function doCreateMainWorkSheet(callback) {
    console.log('create worksheet');
    apiCall('/worksheets/' + documentKey + '/private/full', callback, {
    	'headers': { 'Content-Type' : 'application/atom+xml' },
		method : 'POST',
		'body': '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gs="http://schemas.google.com/spreadsheets/2006"><title>'+vocTableName+'</title><gs:rowCount>1</gs:rowCount><gs:colCount>'+cellInRow+'</gs:colCount></entry>'
    });
  }
  
  function doAddTerm(term, callback) {
    console.log('Adding a new Term');
  }
  
  return {
    // GETting
    checkDocuments : function(callback) {
      apiCall('/spreadsheets/private/full/', function(resp, xhr) {
        processListResults(resp, xhr, callback);
      }, {});
    },
    checkWorksheets : function(callback) {
      apiCall('/worksheets/' + documentKey + '/private/full/', function(resp, xhr) {
        processWorkSheetResults(resp, xhr, callback);
      }, {});
    },
    
    createVocabulary : function(callback) {
    	doCreateVocabulary(callback);
    },
    
    // POSTing
    addTerm : function(term, callback) {
      var self = this;
      var recall = function() { self.addTerm(term, callback); };
      if (!documentKey) {
        // find our document
        this.checkDocuments(recall);
        return;
      }
      if (!dictionaryWorkSheetPresent) {
        // create a worksheet
        this.checkWorksheets(recall);
        return;
      }
      doAddTerm(term);
    }
  };
};
